package io.kiki.stack.http.feign.form.multipart;

import feign.codec.EncodeException;
import lombok.experimental.FieldDefaults;
import lombok.val;

import static lombok.AccessLevel.PRIVATE;

/**
 * A multiple parameters writer.
 *
 * @author Artem Labazin
 */
@FieldDefaults(level = PRIVATE, makeFinal = true)
public class ManyParametersWriter extends AbstractWriter {

    SingleParameterWriter parameterWriter = new SingleParameterWriter();

    @Override
    public boolean isApplicable(Object value) {
        if (value.getClass().isArray()) {
            Object[] values = (Object[]) value;
            return values.length > 0 && parameterWriter.isApplicable(values[0]);
        }
        if (!(value instanceof Iterable)) {
            return false;
        }
        val iterable = (Iterable<?>) value;
        val iterator = iterable.iterator();
        return iterator.hasNext() && parameterWriter.isApplicable(iterator.next());
    }

    @Override
    public void write(Output output, String boundary, String key, Object value) throws EncodeException {
        if (value.getClass().isArray()) {
            val objects = (Object[]) value;
            for (val object : objects) {
                parameterWriter.write(output, boundary, key, object);
            }
        } else
            if (value instanceof Iterable) {
                val iterable = (Iterable<?>) value;
                for (val object : iterable) {
                    parameterWriter.write(output, boundary, key, object);
                }
            }
    }
}
